package com.ruoyi.education.service.impl;

import java.util.Arrays;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.education.mapper.EduClassMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.education.mapper.EduStudentMapper;
import com.ruoyi.education.domain.EduStudent;
import com.ruoyi.education.service.IEduStudentService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-06
 */
@Service
public class EduStudentServiceImpl implements IEduStudentService 
{
    @Autowired
    private EduStudentMapper eduStudentMapper;

    @Autowired
    private EduClassMapper eduClassMapper;
    /**
     * 查询学生信息
     * 
     * @param id 学生信息主键
     * @return 学生信息
     */
    @Override
    public EduStudent selectEduStudentById(Long id)
    {
        return eduStudentMapper.selectEduStudentById(id);
    }

    /**
     * 查询学生信息列表
     * 
     * @param eduStudent 学生信息
     * @return 学生信息
     */
    @Override
    public List<EduStudent> selectEduStudentList(EduStudent eduStudent)
    {
        return eduStudentMapper.selectEduStudentList(eduStudent);
    }

    /**
     * 新增学生信息
     * 
     * @param eduStudent 学生信息
     * @return 结果
     */
    @Override
    public int insertEduStudent(EduStudent eduStudent)
    {
        //设置创建时间
        eduStudent.setCreateTime(DateUtils.getNowDate());
        eduClassMapper.IncreaseStuCount(eduStudent.getCalssId());
        return eduStudentMapper.insertEduStudent(eduStudent);
    }

    /**
     * 修改学生信息
     * 
     * @param eduStudent 学生信息
     * @return 结果
     */
    @Override
    public int updateEduStudent(EduStudent eduStudent)
    {
        //先去数据库找原班级减人数
        Long calssId = eduStudentMapper.selectEduStudentById(eduStudent.getId()).getCalssId();

        if(calssId.equals(eduStudent.getCalssId()))
        {
            throw new RuntimeException("班级没有变化！");
        }
        else
        {
            eduClassMapper.decrestStuCount(calssId);
            eduClassMapper.IncreaseStuCount(eduStudent.getCalssId());
        }
        eduStudent.setUpdateTime(DateUtils.getNowDate());

        return eduStudentMapper.updateEduStudent(eduStudent);
    }

    /**
     * 批量删除学生信息
     * 
     * @param ids 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteEduStudentByIds(Long[] ids)
    {
        Arrays.stream(ids).forEach(id->{
            Long calssId=eduStudentMapper.selectEduStudentById(id).getCalssId();
            eduClassMapper.decrestStuCount(calssId);
        });
        //修改学生的班级人数数量

        eduStudentMapper.deleteEduStudentByIds(ids);
        return 1;
    }

    /**
     * 删除学生信息信息
     * 
     * @param id 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteEduStudentById(Long id)
    {
        return eduStudentMapper.deleteEduStudentById(id);
    }
}
